//****************************************************************
//* Copyright (c) 2008 Ford Motor Company. All Rights Reserved.
//*
//* $$Workfile:   CurrencyValuesAction.java  $$
//* $$Revision:   1.2  $$
//* $$Author:   TMALDON4  $$
//* $$Date:   Feb 26 2009 07:30:48  $$
//*
//*****************************************************************
package ar.com.ford.it.fullEconomics.view.action;

import java.util.Calendar;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.facade.CurrencyFacade;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesg01Plant;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesm02Currvalue;
import ar.com.ford.it.fullEconomics.util.FullEconomicsDateUtil;
import ar.com.ford.it.fullEconomics.view.form.CurrencyValuesForm;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.facade.FacadeProvider;
import ar.com.ford.it.webengine.struts.AbstractBaseAction;
import ar.com.ford.it.webengine.struts.FordActionMapping;
import ar.com.ford.it.webengine.websession.WebSession;

public class CurrencyValuesAction extends AbstractBaseAction {

    /**
     * Setea el mensaje de "busqueda sin resultados" cuando la busqueda no trae
     * resultados
     * 
     * @param request
     * Request donde se guarda el mensaje
     */
    private void searchWithNoResults(HttpServletRequest request) {
        ActionMessages am = new ActionMessages();
        MessageResources messageResources = (MessageResources) getResources(request);

        am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                "customMessage", messageResources
                        .getMessage("message.noResults")));
        saveMessages(request, am);
    }

    /**
     * Resetea el formulario y envia a la pagina inicial de Currencys
     * 
     */
    public ActionForward initPage(FordActionMapping mapping,
                                  ActionForm actionForm,
                                  HttpServletRequest request,
                                  HttpServletResponse response,
                                  WebSession webSession, ActionMessages msgs,
                                  ActionMessages warns, ActionMessages errorMsgs) {
        ActionMessages am = new ActionMessages();

        CurrencyValuesForm form = (CurrencyValuesForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        form.resetForm();
        CurrencyFacade facadeCurr = (CurrencyFacade) FacadeProvider.getFacade(
                request, CurrencyFacade.class);
        form.setCurrencyOrig(user.getTeesg01Plant().getEesg01CurrencyCodeC()
                .getEesm01CurrencyCodeC());
        form.setCurrencyOrigFind(form.getCurrencyOrig());
        try {
            request.getSession().setAttribute("allCurrency",
                    facadeCurr.getAllCurrency());
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }

        return mapping.findForward("success");
    }

    /**
     * Resetea los campos para el create/update
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward clearCreateFields(FordActionMapping mapping,
                                           ActionForm actionForm,
                                           HttpServletRequest request,
                                           HttpServletResponse response,
                                           WebSession webSession,
                                           ActionMessages msgs,
                                           ActionMessages warns,
                                           ActionMessages errorMsgs) {
        CurrencyValuesForm form = (CurrencyValuesForm) actionForm;

        form.clearCreateUpdateFields();
        return mapping.findForward("success");
    }

    /**
     * Resetea los campos para el Find
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward clearFindFields(FordActionMapping mapping,
                                         ActionForm actionForm,
                                         HttpServletRequest request,
                                         HttpServletResponse response,
                                         WebSession webSession,
                                         ActionMessages msgs,
                                         ActionMessages warns,
                                         ActionMessages errorMsgs) {
        CurrencyValuesForm form = (CurrencyValuesForm) actionForm;

        form.clearFindFields();
        return mapping.findForward("success");
    }

    /**
     * Se encarga del manejo de la busqueda de CurrencyValues
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward findCurrencyValues(FordActionMapping mapping,
                                            ActionForm actionForm,
                                            HttpServletRequest request,
                                            HttpServletResponse response,
                                            WebSession webSession,
                                            ActionMessages msgs,
                                            ActionMessages warns,
                                            ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();

        CurrencyValuesForm form = (CurrencyValuesForm) actionForm;
        CurrencyFacade facade = (CurrencyFacade) FacadeProvider.getFacade(
                request, CurrencyFacade.class);
        Collection<Teesm02Currvalue> res = null;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        Teesg01Plant plant = user.getTeesg01Plant();
        try {
            res = facade.findCurrencyValues(plant, form.getFechaFind(), form
                    .getCurrencyOrigFind(), form.getCurrencyDestFind());
            if (res.isEmpty()) {
                searchWithNoResults(request);
            }
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        // si estoy en delete, seteo los atributos para continuar con el borrado
        if (form.getSection().equalsIgnoreCase("delete")) {
            form.setShowConfirmMoveDate((String) request
                    .getAttribute("showConfirmMoveDate"));
            form.setCurrencyValueSelected((Teesm02Currvalue) request
                    .getAttribute("currValueToDelete"));
            form.setConfirmMovePrevDate("false");
        }
        form.setCurrencyValues(res);
        form.clearCreateUpdateFields();
        return mapping.findForward("success");
    }

    /**
     * Setea los campos de edicion de Currencys con los valores del Currency
     * seleccionado mediante el listado
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward editCurrencyValue(FordActionMapping mapping,
                                           ActionForm actionForm,
                                           HttpServletRequest request,
                                           HttpServletResponse response,
                                           WebSession webSession,
                                           ActionMessages msgs,
                                           ActionMessages warns,
                                           ActionMessages errorMsgs) {
        CurrencyValuesForm form = (CurrencyValuesForm) actionForm;

        form.setCurrencyForEdit(form.getCurrencyValueSelected());
        return mapping.findForward("success");
    }

    /**
     * En caso de que se haya seleccionado algun Currency value del listado,
     * entonces lo actualiza, sino llama al metodo encargado de crear el
     * Currency value. En caso de que se haya modificado la fecha de inicio,
     * crea un nuevo currency value eliminando el seleccionado, se hace esto
     * porque la fecha de inicio es parte del primay key del currency value.
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward createUpdateCurrency(FordActionMapping mapping,
                                              ActionForm actionForm,
                                              HttpServletRequest request,
                                              HttpServletResponse response,
                                              WebSession webSession,
                                              ActionMessages msgs,
                                              ActionMessages warns,
                                              ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();

        CurrencyValuesForm form = (CurrencyValuesForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        CurrencyFacade facade = (CurrencyFacade) FacadeProvider.getFacade(
                request, CurrencyFacade.class);

        try {
            // Si la moneda existe por codigo
            if (StringUtils.isBlank(form.getFechaOut()))
                form.setFechaOut(FullEconomicsDateUtil.maxDateStr());

            if (form.getEditBlocked().equals("false")) {
                if (facade.validRange(user.getTeesg01Plant(), form
                        .getCurrencyOrig(), form.getCurrencyDest(), form
                        .getFechaIn(), form.getFechaOut())) {
                    facade.createCurrencyValue(form.getCurrencyOrig(), form
                            .getCurrencyDest(), form.getConvertRate(), form
                            .getFechaIn(), form.getFechaOut(), user);

                } else {
                    am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                            "currencyValues.error.invalidRange"));
                    saveErrors(request, am);
                }
            } else {
                Calendar calFechaIn = Calendar.getInstance();
                calFechaIn.setTime(form.getCurrencyValueSelected()
                        .getEesm02CurrencyValueDateY());
                String strFechaIn = FullEconomicsDateUtil.format(calFechaIn);
                if (!strFechaIn.equals(form.getFechaIn())) {
                    facade.deleteCurrencyValue(form.getCurrencyValueSelected(),
                            "true");
                    if (facade.validRange(user.getTeesg01Plant(), form
                            .getCurrencyOrig(), form.getCurrencyDest(), form
                            .getFechaIn(), form.getFechaOut())) {
                        facade.createCurrencyValue(form.getCurrencyOrig(), form
                                .getCurrencyDest(), form.getConvertRate(), form
                                .getFechaIn(), form.getFechaOut(), user);

                    } else {
                        facade.reInsertCurrencyValue(form
                                .getCurrencyValueSelected());
                        am.add(ActionMessages.GLOBAL_MESSAGE,
                                new ActionMessage(
                                        "currencyValues.error.invalidRange"));
                        saveErrors(request, am);
                    }
                } else {
                    facade.updateCurrencyValue(form.getCurrencyOrig(), form
                            .getCurrencyDest(), form.getConvertRate(), form
                            .getFechaIn(), form.getFechaOut(), user);

                }
            }
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * Elimina el Currency seleccionado
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward deleteCurrencyValue(FordActionMapping mapping,
                                             ActionForm actionForm,
                                             HttpServletRequest request,
                                             HttpServletResponse response,
                                             WebSession webSession,
                                             ActionMessages msgs,
                                             ActionMessages warns,
                                             ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();

        CurrencyValuesForm form = (CurrencyValuesForm) actionForm;
        CurrencyFacade facade = (CurrencyFacade) FacadeProvider.getFacade(
                request, CurrencyFacade.class);

        try {
            if (!facade.deleteCurrencyValue(form.getCurrencyValueSelected(),
                    form.getConfirmMovePrevDate())) {
                request.setAttribute("showConfirmMoveDate", "true");
                request.setAttribute("currValueToDelete", form
                        .getCurrencyValueSelected());
            } else {
                request.setAttribute("showConfirmMoveDate", "false");
            }
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }
}
